
module Facebooker::Rails::DelayedUserAction
  def self.included(base)
    base.class_eval do
      alias_method_chain :send_message,:delayed
    end
  end

  def delayed(*args)
    if args.empty?
      @delayed
    else
      @delayed = args.first
    end
  end

  def send_message_with_delayed(message)
    @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients]
    if from.nil? and @recipients.size==1 and requires_from_user?(from,_body)
      @from = @recipients.first
    end
    # notifications can 
    # omit the from address
    raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || !requires_from_user?(from,_body)
    if _body.is_a?(Facebooker::Rails::Publisher::UserAction) && delayed
      ::UserAction.create :user_id=>@from,:feed=>self
    else
      send_message_without_delayed(message)
    end
  end

  def send_delayed_message
    Facebooker::Session.current.publish_user_action(_body.template_id,_body.data||{},_body.target_ids,_body.body_general)
  end

end


Facebooker::Rails::Publisher.send(:include,Facebooker::Rails::DelayedUserAction)
